<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;
use think\Config;

class SystemNotification extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 列表
     */
    public function index()
    {
        if(UID == 1){
            $role_id = 0;
        }else{
            $role_id = Db::name('admin_role_user')
                ->where('user_id',UID)
                ->value('role_id');
        }

        $list_1 = Db::name('system_notification')
            ->where('from_account',UID)
            ->where('is_from',1)
            ->where('is_delete',0)
            ->where('status','unfinished')
            ->order('id desc')
            ->select();

        $list_2 = Db::name('system_notification')
            ->where('send_department',$role_id)
            ->where('is_from',0)
            ->where('is_delete',0)
            ->where('status','unfinished')
            ->order('id desc')
            ->select();

        $list = array_merge($list_1,$list_2);

        Db::name('system_notification')
            ->where('from_account',UID)
            ->where('is_from',1)
            ->where('is_delete',0)
            ->where('status','unfinished')
            ->update(['is_read'=>1]);

        Db::name('system_notification')
            ->where('send_department',$role_id)
            ->where('is_from',0)
            ->where('is_delete',0)
            ->where('status','unfinished')
            ->update(['is_read'=>1]);

        $list_finish_1 = Db::name('system_notification')
            ->where('from_account',UID)
            ->where('is_from',1)
            ->where('is_delete',0)
            ->where('status','finished')
            ->order('id desc')
            ->select();

        $list_finish_2 = Db::name('system_notification')
            ->where('send_department',$role_id)
            ->where('status','finished')
            ->where('is_delete',0)
            ->order('id desc')
            ->select();

        //合并
        $list_finish_temp = array_merge($list_finish_1,$list_finish_2);

        if(count($list_finish_temp) > 0){
            //排序
            foreach ($list_finish_temp as $key => $val) {
                $tmp[$key] = $val['finish_time'];
            }
            array_multisort($tmp,SORT_DESC,$list_finish_temp);

            //去重
            $serializeArrs = array_map('serialize',$list_finish_temp);
            $uniqueArrs = array_unique($serializeArrs);
            $list_finish = array_map('unserialize',$uniqueArrs);
        }else{
            $list_finish = $list_finish_temp;
        }


        $this->view->assign("uid", UID);
        $this->view->assign("list", $list);
        $this->view->assign("list_finish", $list_finish);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add(Request $request){

        if($request->isAjax()){
            $data = input();

            $department = [];
            if(isset($data['dispatch']) && $data['dispatch'] == 1){
                $department[] = '3';
            }
            if(isset($data['order']) && $data['order'] == 1){
                $department[] = '4';
            }
            if(isset($data['hotel']) && $data['hotel'] == 1){
                $department[] = '5';
            }
            if(isset($data['finance']) && $data['finance'] == 1){
                $department[] = '6';
            }
            if(count($department) < 1){
                return ajax_return_adv_error('请选择要通知的部门');
            }
            if(!$data['content'] || empty($data['content'])){
                return ajax_return_adv_error('发送内容不能为空');
            }
            if(!is_numeric($data['is_check'])){
                return ajax_return_adv_error('请选择是否需要处理反馈');
            }
            if($data['is_check']== 1 || $data['is_check'] == 0){
                $is_check = $data['is_check'];
            }else{
                return ajax_return_adv_error('是否需要处理反馈请选择“是”或“否”');
            }

            $supplement_sign = '';
            $supplement_data = '';

            //补充数据
            if(isset($data['supplement_data'])){
                $supplement_sign = '123';
                $supplement_data = '123';
            }

            //用户角色
            if (UID === 1) {
                $role_id = 0;
            } else {
                $role_id = Db::name('admin_role_user')
                    ->where('user_id',UID)
                    ->value('role_id');
            }

            Db::startTrans();
            try{
                $parent_insert = [
                    'content' => $data['content'],
                    'from_account' => UID,
                    'send_department' => $role_id,
                    'status' => 'unfinished',
                    'is_read' => 0,
                    'supplement_sign' => $supplement_sign,
                    'supplement_data' => $supplement_data,
                    'is_from' => 1,
                    'is_check' => $is_check,
                    'parent_id' => 0,
                    'from_department' => $role_id,
                    'create_time' => time(),
                ];
                $parent_id = Db::name('system_notification')->strict(false)->insertGetId($parent_insert);
                $insert = [];
                foreach ($department as $k => $v){
                    $insert[] = [
                        'content' => $data['content'],
                        'from_account' => UID,
                        'send_department' => $v,
                        'status' => 'unfinished',
                        'is_read' => 0,
                        'supplement_sign' => $supplement_sign,
                        'supplement_data' => $supplement_data,
                        'is_from' => 0,
                        'is_check' => $is_check,
                        'parent_id' => $parent_id,
                        'from_department' => $role_id,
                        'create_time' => time(),
                    ];
                }
                $res = Db::name('system_notification')->strict(false)->insertAll($insert);
                if($res){
                    Db::commit();
                    return ajax_return_adv('添加通知成功');
                }else{
                    Db::rollback();
                    return ajax_return_adv_error('添加通知失败');
                }
            }catch (\Exception $e){
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }
        }else{
            return $this->view->fetch();
        }
    }

    /**
 * 处理完成
 */
    public function finished(){
        $id = input('id');
        if(!$id){
            return ajax_return_adv_error('缺少参数id');
        }
        $info = Db::name('system_notification')->where('id',$id)->find();
        if($info['is_from'] == 1 && $info['is_check']){
            $son_info = Db::name('system_notification')->where('parent_id',$info['id'])->select();
            $is_true = true;
            $role = '';
            foreach ($son_info as $k => $v){
                if($v['status'] == 'unfinished'){
                    $temp = Db::name('admin_role')->where('id',$v['send_department'])->value('name');
                    $role .= $temp.'、';
                    $is_true = false;
                }
            }
            if($is_true){
                $res = Db::name('system_notification')->strict(false)->where('id',$id)->update(['status' => 'finished','finish_time'=>time()]);
            }else{
                return ajax_return_adv_error($role.'未处理完成');
            }
        }else{
            $res = Db::name('system_notification')->strict(false)->where('id',$id)->update(['status' => 'finished','finish_time'=>time()]);
        }
        if($res){
            return ajax_return_adv('操作成功');
        }else{
            return ajax_return_adv_error('操作失败');
        }
    }

    /**
     * 系统通知
     */
    public function sys_notifi(){
        if(UID == 1){
            $role_id = 0;
        }else{
            $role_id = Db::name('admin_role_user')
                ->where('user_id',UID)
                ->value('role_id');
        }

        $list_1 = Db::name('system_notification')
            ->where('from_account',UID)
            ->where('is_from',1)
            ->where('status','unfinished')
            ->order('id desc')
            ->select();

        $list_2 = Db::name('system_notification')
            ->where('send_department',$role_id)
            ->where('is_from',0)
            ->where('status','unfinished')
            ->order('id desc')
            ->select();

        $list_read_1 = Db::name('system_notification')
            ->where('from_account',UID)
            ->where('is_from',1)
            ->where('is_read',0)
            ->where('status','unfinished')
            ->order('id desc')
            ->select();

        $list_read_2 = Db::name('system_notification')
            ->where('send_department',$role_id)
            ->where('is_from',0)
            ->where('is_read',0)
            ->where('status','unfinished')
            ->order('id desc')
            ->select();

        $list = array_merge($list_1,$list_2);
        $list_read = array_merge($list_read_1,$list_read_2);

        $num = count($list);
        $un_read_num = count($list_read);
        $str = '';
        if($un_read_num > 0){
            $str .= '您有'.$un_read_num.'条系统通知未读';
        }
        if($num > 0){
            if(!empty($str)){
                $str .= '，有'.$num.'系统通知未处理完成';
            }else{
                $str .= '您有'.$num.'系统通知未处理完成';
            }
        }
        if(!empty($str)){
            $str .= '，请及时处理。';
            return ajax_return_adv($str);
        }else{
            return ajax_return_adv_error('false');
        }
    }

    public function get_message(){
        if(UID == 1){
            $data = input();
            $role_id = 0;
            $list_1 = Db::name('system_notification')
                ->where('from_account',UID)
                ->where('is_from',1)
                ->where('status','unfinished')
                ->field('id')
                ->order('id desc')
                ->select();

            $list_2 = Db::name('system_notification')
                ->where('send_department',$role_id)
                ->where('is_from',0)
                ->where('status','unfinished')
                ->field('id')
                ->order('id desc')
                ->select();
            $list = array_merge($list_1,$list_2);
            $num = count($list);
            if($data['num'] && $data['num'] != $num){
                $str = "您还有".$num."条系统通知未处理";
                return ajax_return_adv($str,'','','','',$num);
            }else{
                return ajax_return_adv_error('false');
            }


        }else{
            $role_id = Db::name('admin_role_user')
                ->where('user_id',UID)
                ->value('role_id');

            $info = Db::name('system_notification')
                ->where('send_department',$role_id)
                ->where('is_from',0)
                ->where('is_read',0)
                ->where('is_notified',0)
                ->order('create_time desc')
                ->select();

           Db::name('system_notification')
                ->where('send_department',$role_id)
                ->where('is_from',0)
                ->where('is_read',0)
                ->where('is_notified',0)
                ->order('create_time desc')
                ->update(['is_notified'=>1]);

            if($info){

                if(UID == 1){
                    $role_id = 0;
                }else{
                    $role_id = Db::name('admin_role_user')
                        ->where('user_id',UID)
                        ->value('role_id');
                }

                $list_1 = Db::name('system_notification')
                    ->where('from_account',UID)
                    ->where('is_from',1)
                    ->where('status','unfinished')
                    ->order('id desc')
                    ->select();

                $list_2 = Db::name('system_notification')
                    ->where('send_department',$role_id)
                    ->where('is_from',0)
                    ->where('status','unfinished')
                    ->order('id desc')
                    ->select();
                $list = array_merge($list_1,$list_2);
                $unfinished_num = count($list);

                if($info[0]['from_department'] == 0){
                    $temp = '超级管理员';
                }else{
                    $temp = Db::name('admin_role')->where('id',$info[0]['from_department'])->value('name');
                }
                $str = '您有最新的通知：'.$info[0]['content'].'，来源于：'.$temp;
                if(count($info)>1){
                    $str .= '，您还有'.count($info).'条通知未读。';
                }
                return ajax_return_adv($str,'','','','',$unfinished_num);
            }else{
                return ajax_return_adv_error('false');
            }
        }
    }

    /**
     * 删除
     */
    public function delete(){
        $id = input('id');
        if(!$id){
            return ajax_return_adv_error('缺少参数id');
        }

        $info = Db::name('system_notification')->where('id',$id)->find();

        if(!$info){
            return ajax_return_adv_error('不存在该信息');
        }

        if($info['status'] != 'finished'){
            return ajax_return_adv_error('未处理完成不可进行删除');
        }

//        $res = Db::name('system_notification')->where('id',$id)->delete();
        $res = Db::name('system_notification')->strict(false)->where('id',$id)->update(['is_delete'=>1]);

        if($res){
            return ajax_return_adv('删除成功');
        }else{
            return ajax_return_adv_error('删除失败或已删除');
        }
    }
}
